#include "StdAfx.h"
#include "Trace.h"

CTrace CTrace::m_trace;

// Purpose:
//		Write log message into the log file
// Inputs:
//		pstrLogMsg - the log message
//		dwBytes - Number of bytes to be written to the file
BOOL CTrace::WriteLine(LPCTSTR lpszLogMsg)
{
	BOOL bStatus = FALSE;
    DWORD dwWrittenBytes = 0;
	size_t nLogMsgLen = 0;
    m_trace.Init();
	
	if (m_trace.m_hLogFile && m_trace.m_hLogFile != INVALID_HANDLE_VALUE && lpszLogMsg)
    {
        // Append data to end of file
        //SetFilePointer(m_trace.m_hLogFile, 0, 0, FILE_END);    
		StringCchLength(lpszLogMsg, STRSAFE_MAX_CCH, &nLogMsgLen);
		nLogMsgLen = nLogMsgLen * sizeof(TCHAR);
        bStatus = WriteFile(m_trace.m_hLogFile, lpszLogMsg, nLogMsgLen, &dwWrittenBytes, NULL);
        bStatus = WriteFile(m_trace.m_hLogFile, _T("\r\n"), 4, &dwWrittenBytes, NULL);
    }
    //Trace class errors shouldnt stop app from working. Ignore and proceed without logging
	return bStatus;
}

// Purpose:
//		Initialize log file name and create log file
// Inputs:
//		None
void CTrace::Init()
{
	LPTSTR szPath = NULL;
    size_t dwFileNameSize = 0;
    size_t dwFileFullPathSize = 0;
	HRESULT hr = S_OK;

	if(!m_trace.m_szLogFile)
    {
		//get temp path
		size_t dwCount = GetTempPath(0, szPath);
		szPath = new TCHAR[dwCount+1];
		dwCount = GetTempPath(dwCount+1, szPath);

		hr = StringCchLength(LOG_FILE_NAME, STRSAFE_MAX_CCH, &dwFileNameSize);
		if(SUCCEEDED(hr))
		{
			dwFileFullPathSize = dwCount + dwFileNameSize + 1;
			m_trace.m_szLogFile = new TCHAR [dwFileFullPathSize];
			StringCchPrintf(m_trace.m_szLogFile, dwFileFullPathSize, _T("%s%s"), szPath, LOG_FILE_NAME);
		}
		delete [] szPath;
	}
	if(m_trace.m_szLogFile && !m_trace.m_hLogFile)
	{
		m_trace.m_hLogFile = CreateFile(
					m_trace.m_szLogFile,
					GENERIC_READ | GENERIC_WRITE,
					FILE_SHARE_WRITE,
					NULL,
					CREATE_ALWAYS,
					FILE_ATTRIBUTE_NORMAL,
					NULL
					);
	}
    //Trace class errors shouldnt stop app from working. Ignore and proceed without logging
}

CTrace::~CTrace()
{
	if(m_szLogFile)
	{
		delete [] m_szLogFile;
		m_szLogFile = NULL;
	}

    //close the log file
    if(m_hLogFile && m_hLogFile != INVALID_HANDLE_VALUE)
    {
        CloseHandle(m_hLogFile);
		m_hLogFile = NULL;
    }
}

CTrace::CTrace() : m_hLogFile (NULL), m_szLogFile(NULL)
{
	Init();
}
